package org.xs.web.http.i18n;


import java.util.Date;
import java.util.Locale;

import org.xs.web.http.S;

public class Location {
	public static final String DFLT_NAME="i18n";
	private static final String KEY = "i18n.location.session.key";
	private static final String LOCALE_KEY="i18n.locale.session.key";
	 
	private long lastModify=0l;
	
	private Locale locale; 
    private Properties pros;
    
	private Location(){
		
	}
	private Location init(Locale locale){
		this.locale = locale;
		this.lastModify = new Date().getTime();
		pros = LocationRule.properties(locale, DFLT_NAME);
		return this;
	}
	
	public long lastModify(){
		if(pros.change()){
			return new Date().getTime();
		}
		return lastModify;
	}
	
	public Locale getLocale(){
		return locale;
	}
	
	public MessageMap message(){
		return  pros.load();
	}
	
	public String message(String key){
		return message().get(key);
	}
	
	public static Location create(Locale locale){
		try {
			Location loc = (Location) S.session().get(KEY);
			if(loc == null || !loc.getLocale().getLanguage().equals(locale.getLanguage())){
				loc = new Location().init(locale);
				S.session().set(KEY, loc);
			} 
			return loc;
		} catch (Exception e) {
			//if running on no container
		}
		return new Location().init(locale);
	}
	
	public static void changeLocale(Locale locale){
		try {
			S.session().set(LOCALE_KEY, locale);
		} catch (Exception e) {
			//if running on no container
		}
	}
	
	public static Location create(){
		try {
			Locale loc= (Locale) S.session().get(LOCALE_KEY);
			if(loc == null){
				loc = Locale.getDefault();
				S.session().set(LOCALE_KEY, loc);
			}
			return create(loc);
		} catch (Exception e) {
			//if running on no container
		}
		return create(Locale.getDefault());
	}	
}
